﻿#pragma execution_character_set("utf-8")
#ifndef BASEMANAGER_H
#define BASEMANAGER_H

#include <QObject>
#include <QJsonObject>
#include <QWidget>
#include <QMenu>
#include "BaseFactory.h"
#include "JsonUtils.h"
#include "apputils.h"
#include "WidgetUtils.h"

//模板模式
class BaseManager : public QObject
{
    Q_OBJECT
public:
    explicit BaseManager(QObject *parent = nullptr);
    virtual void InitConfig();

    QString GetIconPath(QString name);
    QString GetFriendlyName(QString name);
    QStringList GetNames();

    virtual QWidget* GetConfigWidget(QString name);

    void SetFactory(BaseFactory *factory);

    template <typename T1>
    int Register()
    {
        return _factory->Register<T1>();
    }

    //和配置相关
    QString ManagerName();
    void InitMenu(QMenu *menu);
    virtual void WaitForEnd();

public:
    template <typename T>
    T* GetItem(QString name)
    {
        for(auto item:_allItems)
        {
            if(item->name()==name)
            {
                T *ret=dynamic_cast<T*>(item);
                if(ret==nullptr)
                {
                    throw QString("%1 dynamic_cast转型失败").arg(name);
                }
                return ret;
            }
        }
        throw QString("%1 未发现 %2 指令").arg(ManagerName(),name);
    }

    template <typename T>
    QList<T*> GetItems(QJsonArray names)
    {
        QList<T*> ret;
        for(auto name:names)
        {
            T* it=GetItem<T>(name.toString());
            ret.append(it);
        }
        return ret;
    }

    template <typename T>
    QList<T*> GetItems()
    {
        QList<T*> ret;
        for(auto item:_allItems)
        {
            T* it=dynamic_cast<T*>(item);
            ret.append(it);
        }
        return ret;
    }

protected:
    QJsonObject _obj;
    BaseFactory *_factory=nullptr;
    QList<BaseItem*> _allItems;

    virtual void InitImpl(QJsonObject obj);

signals:

public slots:
};

#endif // BASEMANAGER_H
